#!/bin/bash

set -o errexit

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions

set_debug

main() {
	create_infra $namespace
	kubectl_bin delete -f https://github.com/jetstack/cert-manager/releases/download/v${CERT_MANAGER_VER}/cert-manager.yaml 2>/dev/null || :
	sleep 10

	desc 'create PXC cluster without cert manager'
	cluster="some-name"
	spinup_pxc "$cluster" "$conf_dir/$cluster.yml" 3 10 "$conf_dir/secrets_without_tls.yml"
	wait_cluster_consistency "$cluster" 3 2

	desc 'check if certificate issued manually'
	tlsSecretsShouldExist "$cluster-ssl"

	# generation = 2 on this step
	desc 'check disabling tls'
	kubectl_bin patch pxc "$cluster" --type=merge --patch '{"spec": {"tls":{"enabled": false}, "unsafeFlags": {"tls": true}}}' # generation + 1 (total 3)
	sleep 10
	# operator performs:
	# - patch .spec.pause to true (generation = 4)
	# - patch .spec.pause to false (generation = 5)
	wait_cluster_consistency "$cluster" 3 2
	desc 'secrets should be deleted'
	if kubectl get secret "$cluster-ssl" &>/dev/null; then
		echo "error: secret $cluster-ssl exists"
		exit 1
	fi
	if kubectl get secret "$cluster-ssl-internal" &>/dev/null; then
		echo "error: secret $cluster-ssl-internal exists"
		exit 1
	fi
	compare_kubectl "pxc/$cluster"

	desc 'check enabling tls'
	kubectl_bin patch pxc "$cluster" --type=merge --patch '{"spec": {"tls":{"enabled": true}}}' # generation + 1 (total = 6)
	sleep 10
	# operator performs:
	# - patch .spec.pause to true (generation = 7)
	# - patch spec.unsafeFlags.tls to false (generation = 8)
	# - patch .spec.pause to false (generation = 9)
	wait_cluster_consistency "$cluster" 3 2
	compare_kubectl "pxc/$cluster" "-enabled"
	desc 'secrets should be recreated'
	if ! kubectl get secret "$cluster-ssl" &>/dev/null; then
		echo "error: secret $cluster-ssl doesn't exist"
		exit 1
	fi
	if ! kubectl get secret "$cluster-ssl-internal" &>/dev/null; then
		echo "error: secret $cluster-ssl-internal doesn't exist"
		exit 1
	fi

	destroy "$namespace"
	desc "test passed"
}

main
